package com.sixmac.service.impl;

import com.sixmac.core.base.service.BaseService;
import com.sixmac.core.plugins.dao.Blade;
import com.sixmac.core.plugins.dao.Db;
import com.sixmac.core.plugins.dao.Md;
import com.sixmac.core.shiro.ShiroKit;
import com.sixmac.core.toolbox.CMap;
import com.sixmac.core.toolbox.ajax.AjaxResult;
import com.sixmac.core.toolbox.kit.DateKit;
import com.sixmac.core.toolbox.support.Convert;
import com.sixmac.model.Examin;
import com.sixmac.model.ExaminTopic;
import com.sixmac.model.ExaminTopicAnswer;
import com.sixmac.service.ExaminService;
import org.apache.poi.hssf.util.HSSFColor;
import org.jeecgframework.poi.excel.entity.ExportParams;
import org.jeecgframework.poi.excel.entity.params.ExcelExportEntity;
import org.jeecgframework.poi.excel.entity.vo.MapExcelConstants;
import org.jeecgframework.poi.excel.entity.vo.NormalExcelConstants;
import org.springframework.stereotype.Service;
import org.springframework.ui.ModelMap;

import java.util.*;
import java.util.concurrent.ConcurrentHashMap;

/**
 * ExaminServiceImpl
 * 2018-07-09 09:19:09
 *
 * @author Blade
 */
@Service
public class ExaminServiceImpl extends BaseService<Examin> implements ExaminService {


    public static ConcurrentHashMap<String, List> map = new ConcurrentHashMap();


    public String importExcel(ModelMap modelMap) {
        List<ExcelExportEntity> entityList = map.get(ShiroKit.getUser().getId() + "_entityList");
        List<Map<String, Object>> dataResult = map.get(ShiroKit.getUser().getId() + "_dataResult");
        modelMap.put(MapExcelConstants.ENTITY_LIST, entityList);
        modelMap.put(MapExcelConstants.MAP_LIST, dataResult);
        ExportParams exportParams = new ExportParams("数据导出" + " 数据导出表", "导出人账号：" + ShiroKit.getUser().getLoginName() + "      导出时间：" + DateKit.getTime(), "NAME");
        modelMap.put(MapExcelConstants.FILE_NAME, "考试题目" + DateKit.getAllTime());
        exportParams.setColor(HSSFColor.GREY_50_PERCENT.index);
        modelMap.put(NormalExcelConstants.PARAMS, exportParams);
        return MapExcelConstants.JEECG_MAP_EXCEL_VIEW;
    }


    private List<String> getThread() {
        List<String> thead = new ArrayList<>();
        thead.add("题型");
        thead.add("题干");
        thead.add("选项A");
        thead.add("选项B");
        thead.add("选项C");
        thead.add("选项D");
        thead.add("选项E");
        thead.add("选项F");
        thead.add("选项G(选项最多到G)");
        thead.add("答案");
        thead.add("理由");
        thead.add("图片地址");
        thead.add("类型1单选2多择题3判断题");
        return thead;
    }

    public AjaxResult exportExcel(Integer id) {
        List<String> thread = this.getThread();
        String sql = "select t.*,group_concat(a.content)as contents from t_examin_topic t left join t_examin_topic_answer a on a.topicId = t.id where examineId = #{id} group by topicId";
        List<Map> mapList = Db.selectList(sql, CMap.init().put("id", id));
        if (mapList.isEmpty()) {
            return error("章节没到试题");
        }
        List<String> tbody = new ArrayList<>(mapList.size() * 12);


        for (Map map : mapList) {
            tbody.add(this.converChoice(map.get("choice")));
            tbody.add(Convert.toStr(map.get("name")));
            String[] contentString = Convert.toStrArray(Convert.toStr(map.get("contents")));
            String[] contentNew = new String[7];
            System.arraycopy(contentString, 0, contentNew, 0, contentString.length);
            for (String content : contentNew) {
                tbody.add(content);
            }
            tbody.add(this.convertIsTrue(map.get("isTrue")));
            tbody.add(Convert.toStr(map.get("reach")));
            tbody.add(Convert.toStr(map.get("image")));
            tbody.add(Convert.toStr(map.get("choice")));
        }


        String th[] = thread.toArray(new String[0]);
        String tb[] = tbody.toArray(new String[0]);

        return this.importExcel(th, tb);
    }

    public AjaxResult importExcel(String[] thead, String[] tbody) {
        AjaxResult res = AjaxResult.initAjaxResult();
        List<ExcelExportEntity> entityList = new ArrayList<ExcelExportEntity>();
        //内容
        List<Map<String, Object>> dataResult = new ArrayList<Map<String, Object>>();

        if (thead == null || tbody == null) {
            return res.addError("failed");
        }
        int y = 0;
        for (String b : thead) {
            entityList.add(new ExcelExportEntity(b, "table" + (++y)));
        }
        List<String> lists = Arrays.asList(tbody);
        for (int i = 0; i < (tbody.length / thead.length); i++) {
            List<String> list = lists.subList(i * thead.length, (i + 1) * thead.length);
            Map map = new HashMap();
            int a = 0;
            for (String s : list) {
                map.put("table" + (++a), s);
            }
            dataResult.add(map);
        }
//        map.remove(ShiroKit.getUser().getId() + "_entityList");
//        map.remove(ShiroKit.getUser().getId() + "_dataResult");
        map.put(ShiroKit.getUser().getId() + "_entityList", entityList);
        map.put(ShiroKit.getUser().getId() + "_dataResult", dataResult);
        return res.setMessage("success");
    }


    private String convertIsTrue(Object o) {
        String s = Convert.toStr(o);
        return s.replaceAll(",", "").replaceAll("1", "A").replaceAll("2", "B").replaceAll("3", "C").replaceAll("4", "D").replaceAll("5", "E").replaceAll("6", "F").replace("7", "G");

    }

    private String converChoice(Object o) {
        Integer s = Convert.toInt(o);
        String str = null;
        switch (s) {
            case 1:
                str = "单选";
                break;
            case 2:
                str = "多选";
                break;
            case 3:
                str = "判断题";
                break;
        }
        return str;
    }


    @Override
    public AjaxResult saveExamineTopicAnswer(Integer examineId, String name, String reach, String images, String[] content, String[] result, Integer type) {
        AjaxResult res = new AjaxResult();
        Integer length = content.length;
        //问题
        ExaminTopic examinTopic = new ExaminTopic();
        if (result.length == 0) {
            return res.addError("不能没有正确答案");
        }
        if (result.length > 1) {
            //多选
            examinTopic.setChoice(2);
        } else if (length == 2) {
            //判断题
            examinTopic.setChoice(3);
        } else {
            //单选题
            examinTopic.setChoice(1);
        }
        examinTopic.setName(name);
        examinTopic.setType(type);
        examinTopic.setReach(reach);
        examinTopic.setExamineId(examineId);
        examinTopic.setImage(images);
        examinTopic.setCreateTime(new Date());
        examinTopic.setExamineId(examineId);
        StringBuilder sb = new StringBuilder();
        for (String s : result) {
            Integer b = Convert.toInt(s) + 1;
            sb.append(b);
            sb.append(",");
        }
        examinTopic.setIsTrue(sb.substring(0, sb.length() - 1));
        Integer examineTopicId = Blade.create(ExaminTopic.class).saveRtId(examinTopic);
        if (examineTopicId > 0) {
            for (int i = 0; i < content.length; i++) {
                // 问题答案
                ExaminTopicAnswer answer = new ExaminTopicAnswer();
                answer.setTopicId(examineTopicId);
                answer.setContent(content[i]);
                answer.setCreateTime(new Date());
                Blade.create(ExaminTopicAnswer.class).save(answer);
            }
        } else {
            throw new RuntimeException();
        }
        return res.addSuccess("添加成功");
    }

    @Override
    public boolean updateStatus(String ids, Integer status) {
        CMap map = CMap.init().set("status", status).set("ids", Convert.toIntArray(ids));
        boolean temp = updateBy("status = #{status}", "id in (#{join(ids)})", map);
        return temp;
    }

    @Override
    @SuppressWarnings("unchecked")
    public Map<String, Object> findOne(Object id) {
        return Md.selectOne("examin.findOne", CMap.init().set("id", id), Map.class);
    }

}
